import sys
import pygame
import field_object
import time
import random

gridSide = 40
black = 0,0,0
screenWidth = 800
screenHeight = 600
screenSize = screenWidth, screenHeight
innerMenuWidth = 200

class Button:
    def __init__(self, name, screen, leftX, rightX, topY, botY, pictureFileName, pictureOnFileName, pictureHoverName, hover, pictureBackground, hasBackground):
        self.leftX = leftX
        self.rightX = rightX
        self.topY = topY
        self.botY = botY
        self.pictureOff = pygame.image.load(pictureFileName)
        self.pictureOn = pygame.image.load(pictureOnFileName)
        self.hasBackground = hasBackground
        if hasBackground:
            self.pictureBackground = pygame.image.load(pictureBackground) 
        self.hover = hover
        self.name = name
        if hover:
            self.pictureHover = pygame.image.load(pictureHoverName)
        self.mouseInside = False
        self.isClicked = False
        self.isOn = False
        self.screen = screen
    def insideButton(self, x, y):
        return self.leftX <= x <= self.rightX and self.topY <= y <= self.botY
    def switchOn(self):
        self.isOn = not self.isOn
    def draw(self):
        if self.hasBackground:
            rect = self.pictureBackground.get_rect(topleft=(self.leftX, self.topY))
            self.screen.blit(self.pictureBackground, rect)
        if (self.mouseInside and self.hover):
            rect = self.pictureHover.get_rect(topleft=(self.leftX, self.topY))
            self.screen.blit(self.pictureHover, rect)
        elif self.isOn:
            rect = self.pictureOn.get_rect(topleft=(self.leftX, self.topY))
            self.screen.blit(self.pictureOn, rect)
        else:
            rect = self.pictureOff.get_rect(topleft=(self.leftX, self.topY))
            self.screen.blit(self.pictureOff, rect)        
    def processEvent(self, event):
        #if self.name == "itemButton1_1":
            #print "ajojojo"
        self.isClicked = False
        if event.type == pygame.MOUSEBUTTONUP:
            mouseX, mouseY = event.pos
            if self.name == "itemButton1_0":
                print self.isClicked
            self.isClicked = self.insideButton(mouseX, mouseY)
        if event.type == pygame.MOUSEMOTION:
            mouseX, mouseY = event.pos
            if (not self.mouseInside) and self.insideButton(mouseX, mouseY):
                self.mouseInside = True
            elif (self.mouseInside) and (not self.insideButton(mouseX, mouseY)):
                self.mouseInside = False
class CreepGenerator:
    def __init__(self):
        return
        
    def generate(self, char):
        if char == 'a':
            creep = field_object.Creep("frog", "frog.png", 100, 0, 1, 10, 1, 1)
        elif char == 'b':
            creep = field_object.Creep("goblin", "goblin.png", 200, 30, 1, 50, 2, 2)
        elif char == 'c':
            creep = field_object.Creep("sprite", "sprite.png", 50, 10, 2, 70, 2, 1)
        else:
            creep = field_object.Creep("orc", "orc.png", 200, 80, 1, 100, 1, 2)
        
        return creep

class ItemGenerator:
    def __init__(self):
        return
    
    def generate(self, char):
        if char == 'k':
            item = field_object.DamagingItem("Blast scroll", "scroll.png", 200, 1)
        else:
            item = field_object.HealingItem("healing potion", "healing_potion.png",100, 1)
        return item
    
class OverlayGenerator:
    def __init__(self):
        return
    
    def generate(self, char):
        if char == '0' or char == '2':
            overlay = field_object.Overlay("floor", "floor.png", True, True)
        elif char == '1':
            overlay = field_object.Overlay("wall", "wall.png", False, False)
        else:
            overlay = field_object.Overlay("exit", "exit.png", True, True)
        return overlay

class PlayerGenerator:
    def __init__(self):
        self.players = []
    
    def cleanPlayers(self):
        self.players=[]
    
    def acceptPlayer(self, player):
        self.players.append(player)
    
    def generate(self, playerId):
        return self.players[playerId]
    
    def hasMorePlayers(self, playerId):
        return playerId < len(self.players)
        
class Field:
    def __init__ (self, fileName, playerGenerator, creepGenerator, overlayGenerator, itemGenerator):
        fieldFile = open(fileName, "r")
        row = 0
        players = []
        fieldMatrix=[]
        creepDict = {}
        revCreepDict = {}
        playerDict = {}
        visibleAreasDict = {}
        revPlayerDict = {}
        itemDict = {}
        revItemDict = {}
        exits = []
        playerId = 0
        self.controlsMenuPicture = pygame.image.load("controls_bgd.png")
        self.fieldBgd = pygame.image.load("bgd.png")
        for line in fieldFile:
            fieldMatrix.append([])
            #fieldMatrix[row] = []
            column = 0
            for char in line.strip().split(','):                
                #fieldMatrix[row].append([])
                if ord(char) in range(ord('a'), ord('j') + 1):
                    print "creep(" + str(row) + " " + str(column) + ")" + char
                    creep = creepGenerator.generate(char)
                    fieldMatrix[row].append(overlayGenerator.generate('0'))
                    creepDict[creep] = row, column
                    revCreepDict[row, column] = creep
                elif ord(char) in range(ord('k'), ord('t') + 1):
                    print "item(" + str(row) + " " + str(column) + ")" + char
                    fieldMatrix[row].append(overlayGenerator.generate('0'))
                    item = itemGenerator.generate(char)
                    itemDict[item] = row, column
                    revItemDict[row, column] = item
                elif ord(char) in range(ord('0'), ord('3') + 1):
                    print "overlay(" + str(row) + " " + str(column) + ")" + char
                    fieldMatrix[row].append(overlayGenerator.generate(char))
                    if char == '2' and playerGenerator.hasMorePlayers(playerId):
                        player = playerGenerator.generate(playerId);
                        playerDict[player] = row, column
                        visibleAreasDict[player] = [[]]
                        revPlayerDict[row, column] = player
                        players.append(player)#[playerId] = player
                        playerId = playerId+1
                    elif char == '3':
                        exits.append((row, column))
                column=column+1
            row = row+1
        self.fieldMatrix = fieldMatrix
        self.creepDict = creepDict
        self.revCreepDict = revCreepDict                    
        self.playerDict = playerDict
        self.revPlayerDict = revPlayerDict
        self.itemDict = itemDict
        self.revItemDict = revItemDict
        self.rows = row
        self.columns = column
        self.players=players
        self.moveState=0
        self.visibleAreasDict = visibleAreasDict
        self.exits = exits
        self.globalTurn = 0
        print row
        print column
#-------__init__                    
    def drawPicture(self, screen, picture, column, row):    
        x = column * gridSide
        y = row * gridSide 
        pictureRect = picture.get_rect(topleft=(x, y))
        screen.blit(picture, pictureRect)
    def isInsideScreen(self, centerX, centerY, x, y):
        visibleSideInGrids = (screenHeight / gridSide) / 2
        topY = max(0, centerY - visibleSideInGrids)
        botY = min(self.rows - 1, centerY + visibleSideInGrids)
        leftX = max(0, centerX - visibleSideInGrids)
        rightX = min(self.columns - 1, centerX + visibleSideInGrids)
        return topY <= y <= botY and leftX <= x <= rightX
#-------drawPicture            
    def draw(self, screen, playerId):
        screen.fill(black)
        self.drawPicture(screen, self.fieldBgd, 0, 0)
        self.drawPicture(screen, self.controlsMenuPicture, 15, 0)
        player = self.players[playerId]
        if not self.playerDict.has_key(player):
            return
        centerRow, centerColumn = self.playerDict[player]
        visibleSideInGrids = (screenHeight / gridSide) / 2
        topY = max(0, centerRow - visibleSideInGrids)
        botY = min(self.rows - 1, centerRow + visibleSideInGrids)
        leftX = max(0, centerColumn - visibleSideInGrids)
        rightX = min(self.columns - 1, centerColumn + visibleSideInGrids)
        #------draw overlays-----------
        for row in range(topY, botY + 1):
            for column in range(leftX, rightX + 1):
                fieldObj = self.fieldMatrix[row][column]
                # print str(row) + "," + str(column) + " " + str(fieldObj)
                self.drawPicture(screen, fieldObj.picture, visibleSideInGrids - centerColumn + column, visibleSideInGrids - centerRow + row)
        #------draw items-----------
        for item in self.itemDict.keys():
            coords = self.itemDict[item]
            if (self.isInsideScreen(centerColumn, centerRow, coords[1], coords[0])):
                self.drawPicture(screen, item.picture, coords[1] + visibleSideInGrids - centerColumn, coords[0] + visibleSideInGrids - centerRow)
        #------draw creeps-------
        for creep in self.creepDict.keys(): 
            coords = self.creepDict[creep]
            if (self.isInsideScreen(centerColumn, centerRow, coords[1], coords[0])):
                self.drawPicture(screen, creep.picture, coords[1] + visibleSideInGrids - centerColumn, coords[0] + visibleSideInGrids - centerRow)
        #------draw players-------
        for player in self.playerDict.keys():
            coords = self.playerDict[player]
            if (self.isInsideScreen(centerColumn, centerRow, coords[1], coords[0])):
                self.drawPicture(screen, player.picture, coords[1] + visibleSideInGrids - centerColumn, coords[0] + visibleSideInGrids - centerRow)        
        #pygame.display.flip()        
#-------draw
    def offsetCoords(self, playerId, Y, X):
        player = self.players[playerId]
        centerRow, centerColumn = self.playerDict[player]
        visibleSideInGrids = (screenHeight / gridSide) / 2
        return (Y - visibleSideInGrids + centerRow, X - visibleSideInGrids + centerColumn)
#-------offsetCoords        
    def canStep(self, x, y):
        if x >= 0 and x<self.columns and y >= 0 and y <self.rows:
            overlay = self.fieldMatrix[y][x]
            return overlay.passable and (not self.revCreepDict.has_key((y, x))) and (not self.revPlayerDict.has_key((y, x)))
        else:
            return False
#-------canStep        
    def move(self, key, creature, creatureDict, revCreatureDict):
        creatureY, creatureX = creatureDict[creature]
        if key == pygame.K_DOWN:
            newX = creatureX
            newY = creatureY + 1
        elif key == pygame.K_UP:
            newX = creatureX
            newY = creatureY - 1
        elif key == pygame.K_LEFT:
            newX = creatureX - 1
            newY = creatureY
        elif key == pygame.K_RIGHT:
            newX = creatureX + 1
            newY = creatureY
        elif key == pygame.K_SPACE:
            #--Skip turn--
            return True
        else:
            return False
        if self.canStep(newX, newY):
            creatureDict[creature] = newY, newX
            revCreatureDict.pop((creatureY, creatureX))
            revCreatureDict[newY, newX] = creature
            return True
        else:
            return False
#-------move
    def getCreatureCoords(self, creature):
        if (self.playerDict.has_key(creature)):
            creatureY, creatureX = self.playerDict[creature]
        else:
            creatureY, creatureX = self.creepDict[creature]
        return (creatureY, creatureX)
#-------getCreatureCoords        
    def updateCreature(self, creature, attacker):
        if (self.playerDict.has_key(creature)):
            isCreep = False
            creatureY, creatureX = self.playerDict[creature]
        else:
            isCreep = True
            creatureY, creatureX = self.creepDict[creature]
        if creature.hp <= 0:
            if attacker is not None:
                attacker.exp = attacker.exp + creature.expCost
            if isCreep: 
                self.revCreepDict.pop((creatureY, creatureX))
                self.creepDict.pop(creature)
            else:
                self.revPlayerDict.pop((creatureY, creatureX))
                self.playerDict.pop(creature)
            print "creature killed"
#-------updateCreature
    def attack(self, attacker, attackerDict, attackedX, attackedY):
        attackerY, attackerX = attackerDict[attacker]
        atkDistance = field_object.getDistance(attackerX, attackerY, attackedX, attackedY)
        isRangedAttack = abs(attackedY - attackerY) > 1 or abs(attackedX - attackerX) > 1
        if atkDistance > attacker.atkRange or (attackedX == attackerX and attackedY == attackerY) or (isRangedAttack and not self.checkLineOfSight(attackerX, attackedX, attackerY, attackedY)):
            return False; 
        if self.revCreepDict.has_key((attackedY, attackedX)):
            creep = self.revCreepDict[(attackedY, attackedX)]
            attacker.attack(creep)
            #creep.hp -= attacker.getDamage()
            self.updateCreature(creep, attacker)
#            if creep.hp <= 0:
#                #--the creep dies
#                self.revCreepDict.pop((attackedY, attackedX))
#                self.creepDict.pop(creep)
#                print "creep killed"
#                attacker.exp += creep.expCost
            return True;
        elif self.revPlayerDict.has_key((attackedY, attackedX)):
            player = self.revPlayerDict[(attackedY, attackedX)]
            attacker.attack(player)
            self.updateCreature(player, attacker)
            #player.hp -= attacker.getDamage()
#            if player.hp <= 0:
#                #--the player dies
#                self.revPlayerDict.pop((attackedY, attackedX))
#                self.playerDict.pop(player)
            return True;
        else:
            return False;
#-------attack
    def selectTarget(self, attackX, attackY):
        if self.revPlayerDict.has_key((attackY, attackX)):
            return self.revPlayerDict[(attackY, attackX)]
        if self.revCreepDict.has_key((attackY, attackX)):
            return self.revCreepDict[(attackY, attackX)]
        return None  
#-------selectTarget
    def pickItem(self, player, attackX, attackY):
        playerY, playerX = self.playerDict[player]
        if self.revItemDict.has_key((attackY, attackX)) and field_object.getDistance(playerX, playerY, attackX, attackY) < 2 and player.hasInventorySpace():
            item = self.revItemDict[(attackY, attackX)]
            if player.pickItem(item):
                self.revItemDict.pop((attackY, attackX))
                self.itemDict.pop(item)
                return True
            else:
                return False
        else:
            return False
#-------pickItem
    def getLineOfSight(self, x1, x2, y1, y2):
        lineOfSightPoints = [] 
        y = y1
        x = x1  
        dx = x2 - x1; 
        dy = y2 - y1; 
        lineOfSightPoints.append((y1, x1)) 
        if dy < 0: 
            ystep = -1
            dy = -dy
        else: 
            ystep = 1 
        if dx < 0: 
            xstep = -1 
            dx = -dx;
        else: 
            xstep = 1 
        ddy = 2 * dy 
        ddx = 2 * dx 
        if ddx >= ddy:  
            errorprev = error = dx  
            for i in range(0, dx):
                x += xstep; 
                error += ddy; 
                if (error > ddx): 
                    y += ystep; 
                    error -= ddx;  
                    if (error + errorprev < ddx): 
                        lineOfSightPoints.append((y-ystep, x)) 
                    elif (error + errorprev > ddx): 
                        lineOfSightPoints.append((y, x-xstep)) 
                    else: 
                        lineOfSightPoints.append((y-ystep, x)) 
                        lineOfSightPoints.append((y, x-xstep)) 
                lineOfSightPoints.append((y, x)); 
                errorprev = error;  
        else: 
            errorprev = error = dy; 
            for i in range (0, dy):
                y += ystep 
                error += ddx 
                if error > ddy: 
                    x += xstep 
                    error -= ddy 
                    if error + errorprev < ddy: 
                        lineOfSightPoints.append((y, x-xstep)) 
                    elif error + errorprev > ddy: 
                        lineOfSightPoints.append((y-ystep, x)) 
                    else: 
                        lineOfSightPoints.append((y, x-xstep)) 
                        lineOfSightPoints.append((y-ystep, x)) 
                lineOfSightPoints.append((y, x)) 
                errorprev = error    
        #---it's a stub; will implement it
        return lineOfSightPoints
#-------getLineOfSight    
    def checkLineOfSight(self, x1, x2, y1, y2):
        lineOfSight = self.getLineOfSight(x1, x2, y1, y2)
        for (y, x) in lineOfSight:
            overlay = self.fieldMatrix[y][x] 
            if not overlay.visible:
                return False
        return True
#-------checkLineOfSight    
    def checkWeakLineOfSight(self, x1, x2, y1, y2):
        if field_object.getDistance(x1, y1, x2, y2) < 5:
            return True
        else:
            return self.checkLineOfSight(x1, x2, y1, y2)        
#-------checkWeakLineOfSight    
    def moveCreep(self, creep):
        creepY, creepX = self.creepDict[creep]
        print "creep " + str(creepX) + "," + str(creepY)+ " moves"        
        for player in self.playerDict.keys():
            #---Check if there is anyone to attack
            playerY, playerX = self.playerDict[player]
            if (self.attack(creep, self.creepDict, playerX, playerY)):
                return
            #---Check if there is anyone to go to
            if (self.checkWeakLineOfSight(creepX, playerX, creepY, playerY)):
                deltaX = creepX - playerX
                deltaY = creepY - playerY
                if deltaX < 0 and self.canStep(creepX + 1, creepY):
                    self.move(pygame.K_RIGHT, creep, self.creepDict, self.revCreepDict)
                elif deltaX > 0 and self.canStep(creepX - 1, creepY):
                    self.move(pygame.K_LEFT, creep, self.creepDict, self.revCreepDict)
                elif deltaY > 0 and self.canStep(creepX, creepY - 1):
                    self.move(pygame.K_UP, creep, self.creepDict, self.revCreepDict)
                elif self.canStep(creepX, creepY + 1):
                    self.move(pygame.K_DOWN, creep, self.creepDict, self.revCreepDict)
                return                    
            #---Did not return; there was nobody to attack or chase
            direction = random.randint(0, 3)
            if direction == 0:
                self.move(pygame.K_LEFT, creep, self.creepDict, self.revCreepDict)
            elif direction == 1:
                self.move(pygame.K_RIGHT, creep, self.creepDict, self.revCreepDict)
            elif direction == 2:
                self.move(pygame.K_UP, creep, self.creepDict, self.revCreepDict)
            else:
                self.move(pygame.K_DOWN, creep, self.creepDict, self.revCreepDict)
            return
    def moveCreeps(self):
        self.globalTurn = self.globalTurn + 1
        for creep in self.creepDict.keys():
            if self.globalTurn % creep.turnsToWait == 0:
                for i in range(0, creep.moves):
                    self.moveCreep(creep)
        print "-----------------------------"
#-------moveCreeps
    def playerFinished(self, playerId):
        player = self.players[playerId]
        if (self.playerDict.has_key(player)):
            playerY, playerX = self.playerDict[player]
            for (exitY, exitX) in self.exits:
                if (playerY, playerX) == (exitY, exitX):
                    return True
        return False
#-------playerFinished    
class Game:
    def __init__(self):
        self.c_loadPicture = pygame.image.load("c_load.png")
        self.c_savePicture = pygame.image.load("c_save.png")
        self.c_menuPicture = pygame.image.load("c_menu.png")
        self.c_optionsPicture = pygame.image.load("c_options.png")
        self.winner = -1
        self.levels = ["testField.fld", "floor2.fld"]
        #self.consumablePicture = pygame.image.load("cons_bgrd.png")
    def drawControls(self, field, itemButtons, screen, player):
        for i in range(0,16):
            if player.inventory[i] is not None:
                item = player.inventory[i]
                itemButtons[i].pictureOff = item.picture
            else:
                itemButtons[i].pictureOff = itemButtons[i].pictureOn 
        return
    def gameLoop(self, field, screen, playerId):
        player = field.players[playerId]
        field.draw(screen, playerId)
        buttons = []
        saveButton = Button("save", screen, 3*screenWidth/4, 7*screenWidth/8, 0, gridSide, "c_save.png", "c_save.png", "c_save.png", False, "c_save.png", False)
        buttons.append(saveButton)
        loadButton = Button("load", screen, 7*screenWidth/8, screenWidth, 0, gridSide, "c_load.png", "c_load.png", "c_load.png", False, "c_load.png", False)
        buttons.append(loadButton)
        optionsButton = Button("options", screen, 3*screenWidth/4, 7*screenWidth/8, gridSide, 2*gridSide, "c_options.png", "c_options.png", "c_options.png", False, "c_options.png", False)
        buttons.append(optionsButton)
        menuButton = Button("menu", screen, 7*screenWidth/8, screenWidth, gridSide, 2*gridSide, "c_menu.png", "c_menu.png", "c_menu.png", False, "c_options.png", False)
        buttons.append(menuButton)
        
        #itemButtons = [[]]
        
        #leftTopItem  = (3*screenWidth/2, 10*gridSide)
        itemButtons = [] 
        for i in range (0,4):
            #itemButtons.append([])
            for j in range (0,4):
                #itemButtons[i].append([])
                name = "itemButton" + str(i) + "_" + str(j)
                buttons.append(Button(name, screen, 3*screenWidth/4 + i*gridSide + gridSide/2, 3*screenWidth/4 + i*gridSide + gridSide + gridSide/2, 10*gridSide + j*gridSide + gridSide/2, 10*gridSide + j * gridSide + gridSide + gridSide/2, "cons_bgrd.png", "cons_bgrd.png", "cons_bgrd.png", False, "cons_bgrd.png", True))
                itemButtons.append(buttons[-1])
        #for 
        for button in buttons:
            button.draw()
        pygame.display.flip()
        itemTargetSelect = False
        itemTargetSelectIdx = 0
        while 1:
            if (player.hp <= 0):
                print "the player is dead"
                return False
            if (field.playerFinished(playerId)):
                return True;
            time.sleep(0.05)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                else:
                    #---insert buttons processing here
                    for button in buttons:
                        button.processEvent(event)
                    for button in buttons:
                        if button.name == "save":
                            if (button.isClicked):
                                itemTargetSelect = False
                                print "saving..."
                        elif button.name == "load":
                            if (button.isClicked):
                                itemTargetSelect = False                                
                                print "loading..."
                        elif button.name == "options":
                            if (button.isClicked):
                                itemTargetSelect = False                                
                                print "open options menu"
                        elif button.name == "menu":
                            if (button.isClicked):
                                itemTargetSelect = False                                
                                return False
                        else:
                            for i in range(0,4):
                                for j in range(0,4):
                                    buttonName = "itemButton" + str(i) + "_" + str(j)
                                    if (button.name == buttonName):
                                        #print buttonName + " is clicked=" + str(button.isClicked)
                                        if (button.isClicked):
                                            print "Great success!"
                                            if (not itemTargetSelect) and player.hasItem(j + i * 4):
                                                itemTargetSelect = True
                                                itemTargetSelectIdx = j + i * 4
                                        #---button indexed (i,j) is used
                        
                    if event.type == pygame.KEYDOWN:
                        itemTargetSelect = False                                                        
                        if (field.move(event.key, player, field.playerDict, field.revPlayerDict)):
                            #---only have creeps move and redraw the screen if player made his move
                            field.moveCreeps()
                            field.draw(screen, playerId)
                    elif event.type == pygame.MOUSEBUTTONUP:
                        attackX, attackY = event.pos
                        attackX = attackX / gridSide
                        attackY = attackY / gridSide
                        attackY, attackX = field.offsetCoords(playerId, attackY, attackX)
                        if itemTargetSelect:
                            itemTarget = field.selectTarget(attackX, attackY)
                            if (itemTarget):
                                if (player.useItem(itemTargetSelectIdx, itemTarget, field)):
                                    field.moveCreeps()
                                    field.draw(screen, playerId)
                                    itemTargetSelect = False
                                else:
                                    itemTargetSelect = False
                        else:
                            if (field.attack(player, field.playerDict, attackX, attackY)):
                                field.moveCreeps()
                                field.draw(screen, playerId)
                            elif (field.pickItem(player, attackX, attackY)):
                                field.moveCreeps()
                                field.draw(screen, playerId)
                                print "got item"
            self.drawControls(field, itemButtons, screen, player)
            for button in buttons:
                button.draw()
            pygame.display.flip()                            
                    #else
            #---process leveling and other such things here
    def newgameMenu(self, screen):
        inMenu = pygame.image.load("menu.png")
        inMenuRect = inMenu.get_rect()
        screen.blit(inMenu, inMenuRect)
        buttons = []
        newgameButton = Button("start", screen, 3*screenWidth/8, 5*screenWidth/8, screenHeight/5, 3*screenHeight/10, "start.png", "start.png", "start_on.png", True, "start_on.png", False)
        buttons.append(newgameButton)
        for button in buttons:
            button.draw()
        while 1:
            time.sleep(0.05)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                else:
                    for button in buttons:
                        button.processEvent(event)
                    for button in buttons:
                        if button.name == "start":
                            if (button.isClicked):
                                cg = CreepGenerator()
                                og = OverlayGenerator()
                                ig = ItemGenerator()
                                pg = PlayerGenerator()
                                player = field_object.Player("Player", "player.png")
                                #---testing
                                player.inventory[3] = ig.generate("k")
                                pg.acceptPlayer(player)
                                for fieldFileName in self.levels:                                    
                                    testField = Field(fieldFileName, pg, cg, og, ig)
                                    if not self.gameLoop(testField, screen, 0):
                                        #add highscore
                                        return
                                #add highscore and win logo
                                return
            for button in buttons:
                button.draw()
            pygame.display.flip()
    def menu(self, screen):
        menu = pygame.image.load("menu.png")
        menuRect = menu.get_rect()
        screen.blit(menu, menuRect)
        buttons = []
        newgameButton = Button("New game", screen, 3*screenWidth/8, 5*screenWidth/8, screenHeight/5, 3*screenHeight/10, "newgame.png", "newgame.png", "newgame_on.png", True, "newgame_on.png", False)
        buttons.append(newgameButton)
        quitButton = Button("Quit", screen, 3*screenWidth / 8, 5*screenWidth/8, 8 * screenHeight / 10, 9 * screenHeight / 10, "quit.png", "quit.png", "quit_on.png", True, "quit_on.png", False)
        buttons.append(quitButton)
        for button in buttons:
            button.draw()
        while 1:
            time.sleep(0.05) 
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                else:
                    for button in buttons:
                        button.processEvent(event)
                    for button in buttons:
                        if button.name == "New game":
                            if (button.isClicked):
                                self.newgameMenu(screen)
                                screen.blit(menu, menuRect)
                        if button.name == "Quit":
                            if (button.isClicked):
                                pygame.quit()
                                sys.exit()                                
            for button in buttons:
                button.draw()
            pygame.display.flip()
#---The game itself---
pygame.init()
pygame.display.set_caption("Python crawler")
screen = pygame.display.set_mode(screenSize)
game = Game()
game.menu(screen)